# -*- coding: utf-8 -*-
import tornado.web
import tornado.ioloop
import tornado.httpserver 
import tornado.autoreload
from tornado.options import define, options

import os.path

 

define('port', default=8080,type=int) 
define('mongodb_host', default='localhost:27017,localhost:27018,localhost:27019')

application = None

def build_handlers(prefix=None):
    handlers = []
    import apps.common
    
    handlers.extend(apps.common.handlers)
    
    import apps.arena
    handlers.extend(apps.arena.handlers)
    
    import apps.forum
    handlers.extend(apps.forum.handlers)
    
    import apps.myspace
    handlers.extend(apps.myspace.handlers)
    
    import apps.news
    handlers.extend(apps.news.handlers)
    
    import apps.report
    handlers.extend(apps.report.handlers)
    
    import apps.circle
    handlers.extend(apps.circle.handlers)
    
    import apps.message
    handlers.extend(apps.message.handlers)
    
    import apps.file
    handlers.extend(apps.file.handlers)
    
    import apps.im
    handlers.extend(apps.im.handlers)
    
    if prefix is not None:
        for i in range(len(handlers)):
            url = prefix + handlers[i][0]
            handler = handlers[i][1] 
            handlers[i] = (url,handler) 
    return handlers
     
def main():
    tornado.options.parse_command_line()
    settings = dict( 
        debug = True, 
        template_path = os.path.join(os.path.dirname(__file__),'template'),
        upload_path = '/apps/workspace/static/promise/upload', 
        download_url = 'http://localhost/promise/upload', 
        static_url = 'http://localhost/promise',
        cookie_secret = "11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
        autoescape = None,
        login_url = '/auth/login', 
    )
    prefix = None
    handlers = build_handlers(prefix)
    application = tornado.web.Application(handlers,**settings)
    
    import pymongo
    from pymongo import Connection
    conn = Connection(options.mongodb_host) 
    application.db = conn['promise']
    application.cached_users = {} 
    
    server = tornado.httpserver.HTTPServer(application) 
    server.listen(options.port) 
    instance = tornado.ioloop.IOLoop.instance()
    tornado.autoreload.start(instance)
    instance.start()

if __name__ == '__main__':    main()